<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: #ddd;
        }

        #canvas {
            position: absolute;
            top: 20px;
            left: 20px;
            margin: 20px;
            background-color: #fff;
            border: thin inset rgba(100, 150, 230, .5);
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="readout"></div>
    <canvas id="canvas" width="800" height="500"></canvas>
    <script>
        const canvas = document.getElementById('canvas')
        const readout = document.getElementById('readout')
        const ctx = canvas.getContext('2d')
        const spritesheet = new Image();

        drawBackground()
        spritesheet.src = 'running-sprite-sheet.png'
        spritesheet.onload = function () {
            drawSpritesheet()
        }
        canvas.addEventListener('mousemove', function (e) {
            const loc = windowTocanvas(e.clientX, e.clientY)
            drawBackground()
            drawSpritesheet()
            drawLine(loc.x, loc.y)
            updateLoc(loc.x, loc.y)
        })
        // x,y坐标转换为canvas内的坐标
        function windowTocanvas(x, y) {
            const canvasBox = canvas.getBoundingClientRect();
            return {
                x: x - canvasBox.left * (canvas.width / canvasBox.width),
                y: y - canvasBox.top * (canvas.height / canvasBox.height)
            }
        }

        // 画背景线
        function drawBackground() {
            let i = ctx.canvas.height
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.strokeStyle = 'lightgray'
            ctx.lineWidth = 0.5
            while (i > 48) {
                ctx.beginPath();
                ctx.moveTo(0, i)
                ctx.lineTo(canvas.width, i)
                ctx.stroke();
                i -= 12
            }
        }
        // 画图片
        function drawSpritesheet() {
            ctx.drawImage(spritesheet, 0, 0)
        }

        // 画鼠标坐标线
        function drawLine(x, y) {
            ctx.strokeStyle = 'rgba(0,0,230,.8)'
            ctx.lineWidth = 0.5;
            // 画横线
            drawHline(y)
            // 画竖线
            drawVline(x)
        }
        // 画横线
        function drawHline(y) {
            ctx.beginPath();
            ctx.moveTo(0, y)
            ctx.lineTo(canvas.width, y)
            ctx.stroke()
        }
        // 画竖线
        function drawVline(x) {
            ctx.beginPath();
            ctx.moveTo(x, 0)
            ctx.lineTo(x, canvas.height)
            ctx.stroke()
        }
        // 显示坐标
        function updateLoc(x, y) {
            readout.innerHTML = 'x:' + x.toFixed(0) + ',y:' + y.toFixed(0)
        }
    </script>
</body>

</html>